from redis import Redis
from config import REDIS_IP, REDIS_PORT
import pickle
from src.huey_init.pgsql import db_manager

# 正在执行的任务
def fetch_redis_queues(queue_pattern='running_tasks:*'):
    # 连接到 Redis
    r = Redis(host=REDIS_IP, port=REDIS_PORT, db=1)
    # 初始化游标
    cursor = 0
    queue_data = []
    # 遍历所有匹配的键
    while True:
        cursor, keys = r.scan(cursor, match=queue_pattern, count=1000)
        for key in keys:
            queue_data.append(key.decode().split(":")[1])
            # if r.type(key) == b'list':  # 判断是否为 List 类型
            #     queue_data[key.decode()] = [item.decode() for item in r.lrange(key, 0, -1)]
        # 如果游标返回为 0，说明遍历完毕
        if cursor == 0:
            break
    return queue_data
# 待执行的任务,默认的队列中只有待执行的任务
# huey中列表最右边的任务最先执行
def get_tasks_queue():
    r = Redis(host=REDIS_IP, port=REDIS_PORT, db=0)

    queue_name = 'huey.redis.app'
    tasks = r.lrange(queue_name, 0, -1)  # 获取队列中的元素
    tasks.reverse()
    decode_tasks = []
    for item in tasks:
        task = pickle.loads(item)
        decode_tasks.append(task)
    results = []
    revoke_tasks = fetch_redis_queues(queue_pattern='revoke_tasks:*')
    sort = 1
    for i in decode_tasks:
        if i.id not in revoke_tasks:
            results.append({"aiTaskId":i.id,"status":1,"sort":sort})
            sort = sort + 1

    for i in fetch_redis_queues(queue_pattern='running_tasks:*'):
        results.insert(0, {"aiTaskId":i,"status":0,"sort":0})
    return results

# def get_tasks():
def clear_all():
    r = Redis(host=REDIS_IP, port=REDIS_PORT, db=1)
    r.flushall()

def delete_running_key(key):
    r = Redis(host=REDIS_IP, port=REDIS_PORT, db=1)
    r.delete("running_tasks:{}".format(key))


if __name__ == "__main__":
    # res = get_tasks_queue()
    # res2 = fetch_redis_queues()
    # print(res2)
    # clear_all()
    # delete_running_key("47f27880-16bd-42be-8df6-96d12df1403c")
    # res = fetch_redis_queues(queue_pattern='revoke_tasks:*')
    # print(res)
    clear_all()

